package com.xmut.bs.handaccount.activity;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;

import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.base.ToolbarBaseActivity;
import com.xmut.bs.handaccount.bmob.Goods;
import com.xmut.bs.handaccount.bmob.User;
import com.xmut.bs.handaccount.util.CommonUtil;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.xmut.bs.handaccount.util.ImageUtils;
import com.xmut.bs.handaccount.util.SDCardUtil;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author Dollkey
 * Date 2018/4/10 16:43.
 */

public class AddGoodsActivity extends ToolbarBaseActivity {

    @BindView(R.id.add_pic)
    ImageView mAddPic;
    @BindView(R.id.title)
    EditText mTitle;
    @BindView(R.id.price)
    EditText mPrice;
    @BindView(R.id.detail)
    EditText mDetail;
    @BindView(R.id.recycle_view)
    RecyclerView mRecycleView;

    private ProgressDialog insertDialog;
    private ProgressDialog saveDialog;
    private String coverImg;
    private boolean hasVideo;
    private List<String> mList;
    //    private AddImgAdapter mAdapter;
    private CommonAdapter<String> mAdapter;
    public static final int REQUEST_CODE_CHOOSE = 0x01;

    @Override
    protected String getSubTitle() {
        return "添加商品";
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_add_goods;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);
        saveDialog = new ProgressDialog(this);
        saveDialog.setMessage("正在保存商品...");
        saveDialog.setCanceledOnTouchOutside(false);
        mList = new ArrayList<>();
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        mRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecycleView.addItemDecoration(new DividerItemDecoration(mContext, DisplayUtils.dp2px(mContext, 8), getResources().getColor(R.color.white)));
//        mAdapter = new AddImgAdapter(mContext, mList);
        mAdapter = new CommonAdapter<String>(mContext, R.layout.item_img, mList) {
            @Override
            protected void convert(ViewHolder holder, String s, int position) {
                ImageView view = holder.getView(R.id.img);
                GlideApp.with(view)
                        .load(s)
                        .placeholder(R.color.grey300)
                        .centerCrop()
                        .error(R.color.grey300)
                        .into(view);
            }
        };
        mRecycleView.setAdapter(mAdapter);
        initItemTouch();
    }

    private void initItemTouch() {
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof GridLayoutManager) {// GridLayoutManager
                    // flag如果值是0，相当于这个功能被关闭
                    int dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    int swipeFlag = 0;
                    // create make
                    return makeMovementFlags(dragFlag, swipeFlag);
                } else if (layoutManager instanceof LinearLayoutManager) {// linearLayoutManager
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                    int orientation = linearLayoutManager.getOrientation();
                    int dragFlag = 0;
                    int swipeFlag = 0;
                    // 为了方便理解，相当于分为横着的ListView和竖着的ListView
                    if (orientation == LinearLayoutManager.HORIZONTAL) {// 如果是横向的布局
                        swipeFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                        dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    } else if (orientation == LinearLayoutManager.VERTICAL) {// 如果是竖向的布局，相当于ListView
                        dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                        swipeFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    }
                    return makeMovementFlags(dragFlag, swipeFlag);
                }
                return 0;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                mList.remove(viewHolder.getAdapterPosition());
                mAdapter.notifyDataSetChanged();
            }
        });
        mItemTouchHelper.attachToRecyclerView(mRecycleView);
    }

    @Override
    protected void initParams(Intent intent) {

    }

    @OnClick(R.id.add_pic)
    public void onViewClicked() {
        callGallery(999);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_save, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                callGallery(1);
                break;
            case R.id.action_save:
                saveData();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void saveData() {
        if (BmobUser.getCurrentUser(User.class) == null) {
            showToast("请先登录");
            return;
        }
        saveDialog.show();
        mList.add(0, coverImg);
        BmobFile.uploadBatch(mList.toArray(new String[mList.size()]), new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> files, List<String> urls) {
                //1、files-上传完成后的BmobFile集合，是为了方便大家对其上传后的数据进行操作，例如你可以将该文件保存到表中
                //2、urls-上传文件的完整url地址
                int size = urls.size();
                if (size == mList.size()) {//如果数量相等，则代表文件全部上传完成
                    Goods goods = new Goods();
                    goods.setName(mTitle.getText().toString().trim());
                    goods.setDescription(mDetail.getText().toString().trim());
                    goods.setPrice(Float.valueOf(mPrice.getText().toString().trim()));
                    ArrayList<String> urls1 = new ArrayList<>();
                    urls1.add(urls.get(0));
                    goods.setBannerUrls(urls1);
                    if (urls.size() > 1) {
                        urls.remove(0);
                        goods.setDetailUrls(urls);
                    }
                    goods.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            saveDialog.dismiss();
                            if (e == null) {
                                showToast("商品保存成功:");
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                showToast("商品保存失败:" + e.getMessage());
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                saveDialog.dismiss();
                showToast("文章保存失败:" + errormsg);
            }

            //1、curIndex--表示当前第几个文件正在上传
            //2、curPercent--表示当前上传文件的进度值（百分比）
            //3、total--表示总的上传文件数
            //4、totalPercent--表示总的上传进度（百分比）
            @Override
            public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
            }
        });
    }

    /**
     * 调用图库选择
     */
    private void callGallery(int code) {
        //调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");// 相片类型
        startActivityForResult(intent, code);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                    insertImagesSync(data);
                } else if (requestCode == 999) {
                    Uri uri = data.getData();
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
                    int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    actualimagecursor.moveToFirst();
                    int width = CommonUtil.getScreenWidth(mContext);
                    int height = CommonUtil.getScreenHeight(mContext);
                    Bitmap bitmap = ImageUtils.getSmallBitmap(actualimagecursor.getString(actual_image_column_index), width, height);//压缩图片
                    coverImg = SDCardUtil.saveToSdCard(bitmap);
                    GlideApp.with(mAddPic).load(data.getData()).fitCenter().into(mAddPic);
                }
            }
        }
    }

    /**
     * 异步方式插入图片
     *
     * @param data
     */
    private void insertImagesSync(final Intent data) {
        insertDialog.show();
        Observable
                .create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        try {
                            Uri uri = data.getData();
                            Bitmap bitmap;
                            //                            String[] proj = {MediaStore.Images.Media.DATA};
                            ContentResolver cr = mContext.getContentResolver();
                            Cursor cursor = cr.query(uri, null, null, null, null);
                            //                            int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            cursor.moveToFirst();
                            String img_path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                            int width = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH));
                            int height = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT));
                            while (width > 720 || height > 1280) {
                                width = width / 2;
                                height = height / 2;
                            }
                            bitmap = ImageUtils.getSmallBitmap(img_path, width, height);//压缩图片
                            cursor.close();
                            subscriber.onNext(SDCardUtil.saveToSdCard(bitmap));
                            subscriber.onCompleted();
                        } catch (Exception e) {
                            e.printStackTrace();
                            subscriber.onError(e);
                        }
                    }
                })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        insertDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        insertDialog.dismiss();
                        showToast("图片插入失败" + e.getMessage());
                    }

                    @Override
                    public void onNext(String imagePath) {
                        mList.add(imagePath);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

}
